package com.xiaoqiudong.pojo.game;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaoqiudong.pojo.User;
import com.xiaoqiudong.pojo.response.MatchResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
@Component
/**
 * Created with IntelliJ IDEA
 * Descroption
 * User:dell
 * Date:2025-08-16
 * Time:14:32
 */
public class Matcher {
    private Queue<User> normQueue = new LinkedList<>();
    private Queue<User> highQueue = new LinkedList<>();
    private Queue<User> veryHighQueue = new LinkedList<>();

    @Autowired
    private OnlineUserManager onlineUserManager;

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private RoomManager roomManager;

    //操作匹配队列
    public void add(User user){
        if (user.getScore()<2000){
            synchronized (normQueue){
                normQueue.offer(user);
                normQueue.notify();
            }

            System.out.println("玩家："+ user.getUsername()+"进入normQueue");
        }else if(user.getScore()>=2000 && user.getScore()<3000){
            synchronized (highQueue){
                highQueue.offer(user);
                highQueue.notify();
            }

            System.out.println("玩家："+ user.getUsername()+"进入highQueue");
        }else {
            synchronized (veryHighQueue){
                veryHighQueue.offer(user);
                veryHighQueue.notify();
            }

            System.out.println("玩家："+ user.getUsername()+"进入verHighQueue");
        }
    }

    public void remove(User user){
        if (user.getScore()<2000){
            synchronized (normQueue){
                normQueue.remove(user);
            }
            System.out.println("玩家："+ user.getUsername()+"退出normQueue");
        } else if (user.getScore() >= 2000 && user.getScore() < 3000) {
            synchronized (highQueue){
                highQueue.remove(user);
            }
            System.out.println("玩家："+ user.getUsername()+"退出highQueue");

        }else {
            synchronized (veryHighQueue){
                veryHighQueue.remove(user);
            }
            System.out.println("玩家："+ user.getUsername()+"退出veryHighQueue");
        }
    }

    public Matcher(){
        //创建三个线程，扫描三个匹配对列
        Thread t1 = new Thread(){
            @Override
            public void run() {
                while(true){
                    handlerMatch(normQueue);
                }
            }
        };
        t1.start();

        Thread t2 = new Thread(){
            @Override
            public void run() {
                while (true){
                    handlerMatch(highQueue);
                }
            }
        };
        t2.start();

        Thread t3 = new Thread(){
            @Override
            public void run() {
                while(true){
                    handlerMatch(veryHighQueue);
                }
            }
        };
        t3.start();
    }

    private void handlerMatch(Queue<User> matchQueue) {
        synchronized (matchQueue){
            try{
                //检查队列中的元素是否达到2
                while (matchQueue.size()<2){
                    matchQueue.wait();
                }
                //从对列中取出两个玩家
                User player1 = matchQueue.poll();
                User player2 = matchQueue.poll();
                System.out.println("匹配到两个玩家："+player1.getUsername()+","+player2.getUsername());

                //获取websocket会话
                //查看用户的在线状态
                WebSocketSession session1 = onlineUserManager.getGameHall(player1.getUserId());
                WebSocketSession session2 = onlineUserManager.getGameHall(player2.getUserId());
                if (session1 == null){
                    matchQueue.offer(player2);
                    return;
                }
                if (session2 == null){
                    matchQueue.offer(player1);
                    return;
                }
                //当前能否排到两个玩家是同一个用户的情况嘛? 一个玩家入队列了两次??
                //用户多开
                if (session1 == session2){
                    matchQueue.offer(player1);
                    return;
                }

                //放入同一个游戏房间
                Room room = new Room();
                roomManager.add(room,player1.getUserId(),player2.getUserId());

                //反馈信息：匹配到了对手
                MatchResponse matchResponse1 = new MatchResponse();
                matchResponse1.setOk(true);
                matchResponse1.setMessage("matchSuccess");
                String json1 = objectMapper.writeValueAsString(matchResponse1);
                session1.sendMessage(new TextMessage(json1));

                MatchResponse matchResponse2 = new MatchResponse();
                matchResponse2.setOk(true);
                matchResponse2.setMessage("matchSuccess");
                String json2 = objectMapper.writeValueAsString(matchResponse2);
                session2.sendMessage(new TextMessage(json2));
            }catch (JsonProcessingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
